import React, { Component } from 'react';
import {BrowserRouter as Router, Route} from 'react-router-dom';

import Header from './components/header';
import Player from './pages/player';
import MusicList from './pages/musicList';
import './App.scss';
import { MUSIC_LIST } from './config/musicList';
let $ = window.$
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      currenMusic: MUSIC_LIST[0],
      musicList: MUSIC_LIST
    }
  }

  playMusic () {
    $('#player').jPlayer('setMedia', {
      mp3: this.state.currenMusic.file
    }).jPlayer('play')
  }

  changeMusicHandler (state) {
    let index = this.findMusicIndex()
    let checkIndex = 0
    let len = this.state.musicList.length
    if (state === 'next') {
      checkIndex = (index + 1) % len
    } else {
      checkIndex = (index - 1 + len) % len
    }
    this.setState({
      currenMusic: this.state.musicList[checkIndex]
    }, () => {
      this.playMusic()
    })
  }

  findMusicIndex () {
    return this.state.musicList.indexOf(this.state.currenMusic)
  }

  componentDidMount () {
    $('#player').jPlayer({
      supplied: 'mp3',
      wmode: 'window'
    })
    this.playMusic()
  }

  chekMusicHandler (target) {
    this.setState({
      currenMusic: target
    }, () => {
      this.playMusic()
    })
  }

  render() {
    const Home =  () => (
      <Player
        currenMusic={ this.state.currenMusic }
        changeMusic={ this.changeMusicHandler.bind(this) }
      />
    )

    const List = () => (
      <MusicList
        musicList={ this.state.musicList }
        musicItem={ this.state.currenMusic }
        checkMusic={ this.chekMusicHandler.bind(this) }
      />
    )

    return (
      // <div className="App">
      //   <Header></Header>
      //   <Player currenMusic={ this.state.currenMusic } changeMusic={ this.changeMusicHandler.bind(this) }></Player>
      // </div>
      <Router>
        <div>

          <Header></Header>
          <Route exact path="/" component={Home}/>
          <Route path="/list" component={List}/>

        </div>
      </Router>
    );
  }
}

export default App;
